import Taro from "@tarojs/taro";
import { View } from "@tarojs/components";
import React, { useEffect, useState } from "react";

const delay = ms => new Promise(res => setTimeout(res, ms));

async function getOpenid() {
  const openid = Taro.getStorageSync('openid')
  if (!openid) {
    const d = await Taro.request({
      url: `${process.env.PREFIX}/mock-user`,
      method: 'POST'
    })
    Taro.setStorageSync('openid', d.data.data.openid)
    return d.data.data.openid
  } else {
    return openid
  }

}

const useUserState = () => {
  const [user, setUser] = useState({})


  useEffect(() => {
    const openid = Taro.getStorageSync('openid')
    if (!openid) {
      const fetchData = async () => {
        const d = await Taro.request({
          url: `${process.env.PREFIX}/mock-user`,
        })
        setUser(d.data.data)
        Taro.setStorageSync('openid', d.data.data.openid)
      }
      fetchData()
    } else {
      const fetchData = async () => {
        const d = await Taro.request({
          url: `${process.env.PREFIX}/user/${openid}`,
        })
        setUser(d.data.data)
      }
      fetchData()
    }

  }, [])


  return user
}

const Square = (props: any) => {
  const width = props.width || 50
  return (
    <View style={{ width: width + 'px', height: width + 'px', border: '1px solid black' }}>
      {props.children}
    </View>
  )
}

export { Square }
